/**
 *
 */
package org.insia.smartposse.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.DispatchAction;
import org.insia.smartposse.form.LoginForm;
import org.insia.smartposse.manager.UserManager;

/**
 * @author cmougel
 *
 */
public class LoginAction extends DispatchAction {

	/**
	 * If no cmd request view the login page empty
	 */
	@Override
	protected ActionForward dispatchMethod(ActionMapping map, ActionForm form, HttpServletRequest req,
			HttpServletResponse resp, String name) throws Exception {
		if (null == name){
			return map.findForward("home");
		} else {
			return super.dispatchMethod(map, form, req, resp, name);
		}
	}

	/**
	 * Test the login and password
	 * @param map
	 * @param form
	 * @param req
	 * @param resp
	 * @return
	 * @throws Exception
	 */

	public ActionForward login(ActionMapping map, ActionForm form, HttpServletRequest req,
			HttpServletResponse resp) throws Exception {
		LoginForm login = (LoginForm) form;

		if (login.getLogin() != ""){
			UserManager user = new UserManager(login.getLogin());
			if (null != user && user.passwordOk(login.getPassword())){

				req.getSession().setAttribute("User", user);
				req.getSession().setAttribute("user", user.getLogin());
				resp.sendRedirect(req.getContextPath() + "/profile.do");
				return null;
			} else {
				return badlogin(map, req);
			}
		} else {
			return badlogin(map, req);
		}

	}

	/**
	 * Action when the login is Bad
	 * @param map
	 * @param req
	 * @return
	 */
	private ActionForward badlogin(ActionMapping map, HttpServletRequest req) {
		ActionMessages errors = new ActionMessages();
		ActionMessage error = new ActionMessage("errors.login.badrequest");
		errors.add("loginWrong", error);
		saveErrors(req, errors);
		return map.findForward("home");
	}



}
